package org.ucas.faker.web.aop;

import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

public class RequestLogger implements HandlerInterceptor {

  private static Logger logger = LogManager.getLogger(RequestLogger.class);

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // 所有请求第一个进入的方法
    String reqURL = request.getRequestURL().toString();
    String ip = request.getRemoteHost ();

    String parmeter = "{\n";
    Map paras = request.getParameterMap();
    for (Object key: paras.keySet())
    {
      String keyStr = (String)key;
      String[] value = (String[])paras.get(keyStr);
      String valueStr = value.length == 1? value[0] : Arrays.toString(value);
      parmeter +="    " + keyStr + "   :   " + valueStr + " , \n";
    }

    StringBuilder builder = new StringBuilder ();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine ()) != null)
      builder.append (line);
//       System.out.println("请求参数: " + responseStrBuilder.toString ());
    parmeter += builder.toString();
    parmeter += "\n}";

    long startTime = System.currentTimeMillis();
    request.setAttribute("startTime", startTime);
    if (handler instanceof HandlerMethod) {
      StringBuilder sb = new StringBuilder(1000);
      sb.append("-----------------------").append((new Date()).toString()).append("-------------------------------------\n");
      HandlerMethod h = (HandlerMethod) handler;
      //Controller 的包名
      sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
      //方法名称
      sb.append("Method    : ").append(h.getMethod().getName()).append("\n");
      //请求方式  post\put\get 等等
      sb.append("RequestMethod    : ").append(request.getMethod()).append("\n");
      //所有的请求参数
      sb.append("Params    : ").append(parmeter).append("\n");
      //部分请求链接
      sb.append("URI       : ").append(request.getRequestURI()).append("\n");
      //完整的请求链接
      sb.append("AllURI    : ").append(reqURL).append("\n");
      //请求方的 ip地址
      sb.append("request IP: ").append(ip).append("\n");
      logger.info(sb.toString());

    }
//       修改request中的参数并保存到request中
    request.setAttribute("parmeter_json", parmeter);

    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

  }

  @Override
  public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

  }
}
